// utils/payment.js 暂时没用到
const app = getApp(); // 获取全局应用实例
const baseURL = app.globalData.baseURL

let pollingTimer = null
const MAX_POLL_COUNT = 15
const BASE_INTERVAL = 2000

export const startPayment = (orderData) => {
    wx.request({
      url: baseURL + 'api/paymentV3/', // 微信支付V3版本
      method: 'POST',
      dataType: 'json',
      responseType: 'text',
      data: {
        orderData: orderData
      },
      success: (res) => {
        const order = res.data   // 后端传来的统一下单数据
        const orderId = order.out_trade_no  // 后端生成的订单号
        wx.requestPayment({
          timeStamp: order.timeStamp, //'后端生成的时间戳'
          nonceStr: order.nonce_str, //'后端生成的随机字符串'
          package: `prepay_id=${order.prepay_id}`, // 正确拼接
          signType: 'RSA',
          paySign: order.pay_sign, //'后端生成的签名'
          success: () => {
            app.globalData.pendingOrder = orderId
            startStatusPolling(orderId)
          },
          fail: (err) => {
            wx.showToast({ title: '支付取消或失败', icon: 'none' })
          }
        });
      }
  });
}

// 订单状态轮询（指数退避策略）
const startStatusPolling = (orderId) => {
  let pollCount = 0
  let currentInterval = BASE_INTERVAL
  
  const checkStatus = async () => {
    try {
      await wx.request({
        url: baseURL + `api/orders/status?out_trade_no=${orderId}`,
        success: (res) => {
          if (res.data.status === '1') {
            clearInterval(pollingTimer)
            handleSuccess(orderId)
          } else if (pollCount >= MAX_POLL_COUNT) {
            clearInterval(pollingTimer)
            handleTimeout()
          } else {
            pollCount++
            currentInterval = Math.min(currentInterval * 2, 30000) // 最大间隔30秒
          }
        },
      })
    } catch (error) {
      console.error('[状态查询失败]', error)
    }
  }

  pollingTimer = setInterval(checkStatus, currentInterval)
}

// 支付成功处理:跳转到我的页面
const handleSuccess = (orderId) => {
  // wx.showToast({ title: '支付成功,可以完善到订单页了', icon: 'none' })
  wx.reLaunch({
    url: `/pages/my/my?id=${orderId}`,
    success: () => {
      app.globalData.pendingOrder = null
    }
  })
}

// 超时处理
const handleTimeout = () => {
  wx.showModal({
    title: '支付结果确认中',
    content: '请稍后在订单列表查看状态',
    confirmText: '查看订单',
    success: () => {
      wx.switchTab({ url: '/pages/my/my' })
    }
  })
}